package edu.chl.jadetalk.control;

import edu.chl.jadetalk.business.ImageManagerBeanLocal;
import edu.chl.jadetalk.business.upload.ImageDataManagerBeanLocal;
import edu.chl.jadetalk.core.Comment;
import edu.chl.jadetalk.core.CommentThread;
import edu.chl.jadetalk.core.Image;
import edu.chl.jadetalk.core.Rating;
import edu.chl.jadetalk.core.User;
import edu.chl.jadetalk.user.UserSessionBean;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;

/**
 * @author Erik
 */
@ManagedBean
@RequestScoped
public class UploadControllerBean {
    @EJB
    private ImageManagerBeanLocal imageManagerBean;
    
    @EJB
    private ImageDataManagerBeanLocal imageDataManagerBean;
    
    @ManagedProperty(value="#{userSessionBean}")
    private UserSessionBean userSessionBean;

    public void handleFileUpload(FileUploadEvent event) {
        
        User user = userSessionBean.getUser();

        // Upload image to file server
        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.INFO,
                "Uploaded: " + event.getFile().getFileName());
        Logger.getAnonymousLogger().log(Level.INFO, String.format("'%s' upload of size %d.", event.getFile().getFileName(), event.getFile().getSize()));
        
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);

        byte[] imageData = event.getFile().getContents();
        String ext = event.getFile().getFileName().split("\\.")[1];
        String filename = imageDataManagerBean.getFileName(imageData) + "." + ext;
        imageDataManagerBean.saveImageToCache(filename, imageData);
        imageDataManagerBean.uploadImage(filename, imageData);
        
        // Create image entry
        Image image = new Image();
        CommentThread ct = new CommentThread();
        ct.setComments(new LinkedList<Comment>());
        image.setCommentThread(ct);
        image.setImageLocation(filename);
        image.setRatings(new LinkedList<Rating>());
        image.setUser(user);
        
        imageManagerBean.storeImage(image);
        
    }
    
    
    
    public ImageDataManagerBeanLocal getImageManagerBean() {
        return imageDataManagerBean;
    }

    public void setImageManagerBean(ImageDataManagerBeanLocal imageManagerBean) {
        this.imageDataManagerBean = imageManagerBean;
    }
    
    public UserSessionBean getUserSessionBean() {
        return userSessionBean;
    }

    public void setUserSessionBean(UserSessionBean userSessionBean) {
        this.userSessionBean = userSessionBean;
    }

}
